import { Modal } from 'antd-mobile-v2';

/**
 * 拦截表单编辑进行中页面跳转时的弹窗
 * @param {*} props 页面组件的props
 *   使用方式：在目标所在页面添加Prompt组件：
 *      <Prompt message={setRouteBlocker} />
 * 
 */

let lastModal = null;

export const setRouteBlocker = (history, nextRoute) => {
  // const modal = document.querySelector('.am-modal-wrap');
  if (lastModal) {
    // 已有Modal对话框时，不再弹出
    lastModal.close();
    lastModal = null;
    window.history.forward();
    return false;
  }
  if (window.routesBlockerList?.length) {
    lastModal = Modal.alert('您已编辑过内容，确定离开？', '', [
      {
        text: '离开', onPress: () => {
          lastModal = null;
          clearRouteBlocker();
          history.replace({ ...nextRoute });
        }
      },
      {
        text: '留下', onPress: () => {
          lastModal = null;
          window.history.forward();
        }
      }
    ]);
    return false;
  }
  return true;
};



export const clearRouteBlocker = (key) => {
  const targetIndex = window?.routesBlockerList?.indexOf(key);
  if (key) {
    targetIndex > -1 && window.routesBlockerList.splice(targetIndex, 1);
  } else {
    window.routesBlockerList = [];
  }
};


/**
 * 表单改动触发
 */
export const onFormGroupChange = (option) => {
  const { uuid, routeBlock } = option;
  if (routeBlock) {
    window.routesBlockerList = window.routesBlockerList ?? [];
    if (window.routesBlockerList.indexOf(uuid) < 0) { // 表单是否编辑过
      window.routesBlockerList = [...window.routesBlockerList, uuid];
    }
  }
};